import { User } from "server/models/User";
import { generateToken } from "server/utils/auth";
import {
  successResponse,
  errorResponse,
  validationErrorResponse,
} from "server/utils/response";

export default defineEventHandler(async (event) => {
  try {
    const body = await readBody(event);
    const { username, password } = body;

    // 验证输入
    if (!username || !password) {
      return validationErrorResponse("用户名和密码不能为空");
    }

    if (username.length < 3) {
      return validationErrorResponse("用户名至少需要3个字符");
    }

    if (password.length < 6) {
      return validationErrorResponse("密码至少需要6个字符");
    }

    // 验证用户登录
    const user = await User.validateLogin(username, password);    

    if (!user) {
      return errorResponse("用户名或密码错误");
    }

    // 生成JWT token
    const token = generateToken(user);
    setCookie(event, "auth_token", token, {
      maxAge: 60 * 60 * 24 * 7, // 7天有效期
      path: "/",
      sameSite: "strict",
      secure: import.meta.dev ? false : true,
    });

    return successResponse(
      {
        user,
      },
      "登录成功"
    );
  } catch (error) {
    console.error("用户登录失败:", error);
    return errorResponse(
      "登录失败",
      error instanceof Error ? error.message : "未知错误"
    );
  }
});
